//合并二叉树: https://www.nowcoder.com/exam/test/18874168/summary
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
比特就业课
struct node 
{
    node* left;
    node* right;
    int value;
    node() : left(nullptr), right(nullptr), value(0) {}
};

// 此处孩子的编号从1开始计数
void creatTree(vector<node>& treeVec, int num) 
{
    // 按照顺序存储树的各节点，并建立相互之间的联系
    for (int i = 1; i <= num; i++) 
    {
        int l, r, v;
        cin >> l >> r >> v;
        if (l != 0)
        {
            treeVec[i].left = &treeVec[l];
        }
        if (r != 0)
        {
            treeVec[i].right = &treeVec[r];
        }
        treeVec[i].value = v;
    }
}

// 合并树的节点
node* mergeTree(node* root1, node* root2) 
{
    if (root1 != nullptr && root2 != nullptr) 
    {
        root1->left = mergeTree(root1->left, root2->left);
        root1->right = mergeTree(root1->right, root2->right);
        root1->value += root2->value;
        return root1;
    }
    return root1 == nullptr ? root2 : root1;
}

// 层序遍历，使用dfs算法
void leverOrder(node* root) 
{
    queue<node*> q;
    q.push(root);
    while (!q.empty()) 
    {
        node* cur = q.front();
        q.pop();
        cout << cur->value << " ";
        if (cur->left)
        {
            q.push(cur->left);
        }
        if (cur->right)
        {
            q.push(cur->right);
        }
    }
    cout << endl;
}
int main() 
{
    int n, m;
    cin >> n >> m;
    vector<node> treeVec1(n + 1);
    vector<node> treeVec2(m + 1);
    creatTree(treeVec1, n);
    creatTree(treeVec2, m);
    node* root1 = &treeVec1[1];
    node* root2 = &treeVec2[1];
    node* root = mergeTree(root1, root2);
    leverOrder(root);
    return 0;
}